<?php

namespace App\Admin\Controllers;

use App\Models\InventoryFunc;
use App\Models\InTransferBillDetail;

//use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
//use Illuminate\Http\Request;
use Encore\Admin\Widgets\Table;
use Encore\Admin\Widgets\Form as myForm;


class TransferInsController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header('调拨入库管理');
            $content->description('');

            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header('调拨入库管理');
            $content->description('');

            $content->body($this->editForm()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header('调拨入库管理');
            $content->description('');

            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(InTransferBillDetail::class, function (Grid $grid) {
            $grid->model()->select('in_transfer_bill_detail.*','in_transfer_bill_detail.id as detail_id','company.name','transfer_bill.*','admin_users.name as operater_name','sku.name as sku_name','out_warehouse.name as out_warehouse_name','in_warehouse.name as in_warehouse_name')
            ->leftjoin('transfer_bill','transfer_bill.id','=','in_transfer_bill_detail.transfer_bill_id')
            ->leftjoin('company','company.id','=','transfer_bill.company_id')
            ->leftjoin('admin_users','admin_users.username','=','transfer_bill.operater_id')
            ->leftjoin('sku','sku.id','=','in_transfer_bill_detail.sku_id')
            ->leftjoin('warehouse as out_warehouse','out_warehouse.id','=','transfer_bill.out_warehouse_id')
            ->leftjoin('warehouse as in_warehouse','in_warehouse.id','=','transfer_bill.in_warehouse_id')
            ->where('transfer_bill.company_id',Admin::user()->company_id)
            ->orderBy('transfer_bill.created_at', 'desc');
            $grid->transfer_bill_id('调拨单编号')->sortable();
            $grid->sku_name('SKU名称');
            $grid->name('所属公司');
            $grid->operater_name('调度员');
            $grid->send_time('出库时间');
            $grid->out_warehouse_name('调出仓库名称');
            $grid->in_warehouse_name('调入仓库名称');


             $grid->in_state('入库状态')->display(function($v){
                return HelpersController::getStateValue('transferBillState',$v);
            });
            $grid->review_in_state("入库审核状态")->display(function($v){
                return HelpersController::getStateValue('transferBillReviewState',$v);
            });

            $grid->disableCreateButton();//禁用新增按钮
            $grid->disableExport();//禁用导出按钮
            $grid->actions(function ($actions) {
                // append一个操作
                $actions->disableEdit();
                $actions->disableDelete();//禁用删除
                $actions->prepend('<a href="'.\Route('transferIns.show',['id'=>$actions->row['detail_id']]).'"><i class="fa fa-eye"></i></a>');
            });

            $grid->filter(function($filter){

            // 去掉默认的id过滤器
            $filter->disableIdFilter();

            $filter->where(function ($query) {
                    $query->where('in_transfer_bill_detail.transfer_bill_id', 'like', "%{$this->input}%");
                }, '调拨单编号');

            $filter->where(function ($query) {
                    $query->where('sku.name', 'like', "%{$this->input}%");
                }, 'SKU名称');

            $filter->where(function ($query) {
                $query->where('admin_users.name', 'like', "%{$this->input}%");
            }, '调拨员');
            });
        });
    }

    public function show($id)
    {
        $model = new Content();

        $data = \DB::table('in_transfer_bill_detail')->select(
            'inventory.grade',
            'inventory.origin',
            'inventory.colour',
            'inventory.thick',
            'inventory.min_size',
            'inventory.avg_size',
            'sku.name as sku_name',
            'company.name as company_name',
            'admin_users.name as user_name',
            'batch_grade.name as batch_grade',
            'batch_thick.name as batch_thick',
            'batch_origin.name as batch_origin',
            'batch_colour.name as batch_colour',
            //,'warehouse.name as warehouse_name'
            'out_warehouse.name as out_warehouse_name',
            'in_warehouse.name as in_warehouse_name',
            'batch_avg_size.name as batch_avg_size',
            'batch_min_size.name as batch_min_size',
            'reviewer.name as reviewer_name',
            'inventory.inventory_id as bid',
            'transfer_bill.*',
            'in_transfer_bill_detail.*')
            ->leftjoin('transfer_bill','transfer_bill.id','=','in_transfer_bill_detail.transfer_bill_id')
            ->leftjoin('warehouse as out_warehouse','out_warehouse.id','=','transfer_bill.out_warehouse_id')
            ->leftjoin('warehouse as in_warehouse','in_warehouse.id','=','transfer_bill.in_warehouse_id')
            ->leftjoin('admin_users','admin_users.username','=','transfer_bill.operater_id')
            // ->leftjoin('admin_users as documentary','documentary.username','=','agent.merchandiser')
            // ->leftjoin('admin_users as salesman','salesman.username','=','agent.salesman')
            ->leftjoin('admin_users as reviewer','reviewer.username','=','transfer_bill.reviewer_id')
            ->leftjoin('company','company.id','=','transfer_bill.company_id')
            //->leftjoin('warehouse','warehouse.warehouse_id','=','purchase.warehouse_id')
            ->leftjoin('inventory','inventory.id','=','in_transfer_bill_detail.inventory_id')
            ->leftjoin('sku','in_transfer_bill_detail.sku_id','=','sku.id')
            ->leftjoin('batchattribute as batch_grade','inventory.grade','=','batch_grade.id')
            ->leftjoin('batchattribute as batch_thick','inventory.thick','=','batch_thick.id')
            ->leftjoin('batchattribute as batch_origin','inventory.origin','=','batch_origin.id')
            ->leftjoin('batchattribute as  batch_colour','inventory.colour','=','batch_colour.id')
            ->leftjoin('batchattribute as batch_avg_size','inventory.avg_size','=','batch_avg_size.id')
            ->leftjoin('batchattribute as batch_min_size','inventory.min_size','=','batch_min_size.id')
            ->where('in_transfer_bill_detail.id',$id)->first();
        $content = '<div style="width:80%;margin:0 auto;background:#fff;padding:10px;"><h4 style="text-align:center;">基本信息</h4><hr>';
        $headers = [];
        $rows = [
            ['调拨单编号', $data->transfer_bill_id, '物流方式', HelpersController::getStateValue('Logistics',$data->logistics)],
            ['调出仓库',$data->out_warehouse_name,'调入仓库',$data->in_warehouse_name],
            ['所属公司', $data->company_name, '出库时间',$data->send_time]
        ];
        $table_1 = new Table($headers, $rows);
        $content .= $table_1->render();


        $content .= '<h4 style="text-align:center;">系统信息</h4><hr>';

        // table 2
        $headers = [];
        $rows = [
            ['操作人',$data->user_name,'调拨单状态', HelpersController::getStateValue("transferBillState",$data->transfer_bill_out_state)." | ".HelpersController::getStateValue("transferBillState",$data->transfer_bill_in_state)],
            // ['销售',isset($data->salesman)?$data->salesman:'未维护该客户销售','跟单', isset($data->documentary_name)?$data->documentary_name:'未维护该客户跟单' ],
            ['最后操作人',$data->reviewer_name,'最后操作时间',$data->review_time],
            ['单据生成时间', $data->created_at,'',''],
        ];

        $table2 = new Table($headers, $rows);
        $content .= $table2->render();

        $content .= '<h4 style="text-align:center;">批次信息</h4><hr>';

        // table 2
        $headers = [];
        $rows = [
            ['SKU编号',$data->sku_id,'SKU名称', $data->sku_name ],
            ['等级',$data->batch_grade?$data->batch_grade:"未维护",'厚度',$data->batch_thick?$data->batch_thick:"未维护" ],
            ['产地', $data->batch_origin?$data->batch_origin:"未维护",'颜色',$data->batch_colour?$data->batch_colour:"未维护"],
            ['平均尺寸', $data->batch_avg_size?$data->batch_avg_size:"未维护",'最小尺寸',$data->batch_min_size?$data->batch_min_size:"未维护"],
            ['入库状态', HelpersController::getStateValue('inState',$data->in_state),'批次ID',$data->inventory_id]

        ];
        $table_3 = new Table($headers, $rows);

        $content .=  $table_3->render();

        $content .= "<h4 style='text-align:center'>备注</h4><hr><p style='background:#efefef;padding:8px;'>".(trim($data->remark)?$data->remark:"无")."</p>";

        $content .= '<h4 style="text-align:center;">仓库设置</h4><hr>';
        $form = new myForm();
                    // [$data->sku_name,$data->supplier_product_id, $data->num,$data->arrive_time,$data->price,$data->batch_grade,$data->batch_thick,$data->batch_origin,$data->batch_colour,$data->batch_avg_size,$data->batch_min_size]
        $form->__construct(
            [

                'warehouse_id'=>$data->in_warehouse_id,
                // 'warehouse_zone_id'=>$data->warehouse_zone_id,
                // 'warehouse_location_id'=>$data->warehouse_location_id,
                'sku_name'=>$data->sku_name,
                'in_state'=>$data->in_state,
                'bid'=>$data->bid,
                'inventory_id'=>$data->bid

            ]);
        $form->action($data->id.'/finance');
        $form->method('POST');
        $form->disablePjax();
        $form->hidden('in_transfer_bill_detail_id')->default($data->id);
        $form->hidden('transfer_bill_id')->default($data->transfer_bill_id);
        $form->hidden('sku_id')->default($data->sku_id);
        $form->hidden('inventory_sn')->default($data->inventory_id);
        $form->hidden('inventory_id')->default($data->bid);
        $form->hidden('warehouse_id')->default($data->in_warehouse_id);

        $form->display('sku_name','SKU');
        $form->display('bid','批次ID');
        $form->radio('in_state','入库状态')->options(["PART_IN"=>'部分入库',"ALL_IN"=>'全部入库']);
        $hadIn = \DB::table('inventory_checking_detail')->select(\DB::raw('sum(num) as num'),\DB::raw('sum(size) as size'))->where(['checking_ASN'=>$data->transfer_bill_id,'type'=>2,'sku_id'=>$data->sku_id])->first();

        $form->currency('arrive_num','实际入库张数')->symbol("")->help('单据数量： '.$data->num.' ，已入库张数: '.round($hadIn->num,2));

        $form->currency('arrive_size','实际入库尺数')->symbol("")->help('单据数量： '.$data->size.' ，已入库尺数: '.round($hadIn->size,2));
        $form->display('in_warehouse','仓库')->default($data->in_warehouse_name);
        $form->select('warehouse_zone_id','库区')->options(\DB::table('warehouse_zone')->where('warehouse_id',$data->in_warehouse_id)->pluck('name','id'))->load('warehouse_location_id', '/admin/helpers/warehouseLocation');
        $form->select('warehouse_location_id','库位')->options(\DB::table('warehouse_location')->pluck('name','id'));



        if($data->review_in_state == "CHARGE_IN_CHECK"){
            if($data->in_state == "ALL_IN"){
                $content.='<p style="text-align:center"> 已全部入库</p>';
            }else{
                $content .= $form->render();
            }

        }elseif($data->review_in_state == "IN_CHECK"){
            $content.='<p style="text-align:center"> 单据已完成入库</p>';
        }else{
            $content.='<p style="text-align:center">需要等待主管审核通过后操作</p>';
        }
        /*
        $content.='
            <script>
            </script>
        ';
        */
        $items = [
            'header'      => '入库处理',
            'description' => 'in',
            'breadcrumb'  => '',
            'content'     => $content."</div>",
        ];

        return view('admin::content', $items)->render();
    }
    public function finance($id){
        $input = \Illuminate\Support\Facades\Input::all();
        $old = \DB::table('transfer_bill')->where('id',$input['transfer_bill_id'])->first();
        if($old->transfer_bill_in_state == "ALL_IN" ){
            admin_toastr("该SKU已全部入库,如要变更请联系系统管理员",'error');
            return back()->withInput();
        }
        if(!isset($input['in_state'])){
            admin_toastr("入库状态必填","error");
            return back()->withInput();
        }
        if(!$input['warehouse_location_id']){
            admin_toastr("库位必填","error");
            return back()->withInput();
        }
        if(!$input['warehouse_zone_id']){
            admin_toastr("库区必填","error");
            return back()->withInput();
        }
        if(!$input['warehouse_id']){
            admin_toastr("仓库必填","error");
            return back()->withInput();
        }
        if($input['arrive_num']<=0){
            admin_toastr("到货张数至少大于0","error");
            return back()->withInput();
        }

        if($input['arrive_size']<=0){
            admin_toastr("到货尺寸至少大于0","error");
            return back()->withInput();
        }
        if(!$input['inventory_id']){
            admin_toastr("系统错误","error");
            return back()->withInput();
        }
        // if ($validator->fails()) {
        //     return back()->withInput()->withErrors($validator->errors());
        // }

//        $inventory = \DB::table('inventory')->where('inventory.inventory_id',$input['inventory_id'])->first();


        $old_details = \DB::table('in_transfer_bill_detail')->where([['id','<>',$id],['transfer_bill_id',$input['transfer_bill_id']]])->get();
        if(count($old_details) > 0){
            if($input['in_state'] == "PART_IN"){
                $operate_state = "PART_IN";
            }else{
                $operate_state = "ALL_IN";
                foreach ($old_details as $old_detail) {
                    if($old_detail->in_state != "ALL_IN"){
                        $operate_state = "PART_IN";
                        break;
                    }
                }
            }

        }else{
            $operate_state = $input['in_state'];
        }
        $update_order_datas['transfer_bill_in_state'] = $operate_state;

        if($operate_state == "ALL_IN"){
            $update_order_datas['review_in_state'] = "IN_CHECK";
        }
        $model = new InventoryFunc("in_transfer",$id);
        try{
            \DB::beginTransaction();


            $model->insertTransferInventoryAndCheckingOne($input);
            \DB::table('transfer_bill')->where(['id'=>$input['transfer_bill_id']])->update($update_order_datas);
            \DB::table('in_transfer_bill_detail')->where('id',$id)->update(['in_state'=>$input['in_state']]);
            HelpersController::endId('batch_id');
            \DB::commit();
            admin_toastr("入库成功");
            $url = route('transferIns.index');
            return redirect($url);
        }catch (Exception $e) {
            \DB::rollBack();
            admin_toastr("数据库出错，请联系管理员","error");
            return back()->withInput();

        }
    }
}
